package com.ds.infrastructure.hyperspace.console.config.shiro;

import com.ds.infrastructure.hyperspace.console.service.impl.AuthService;
import com.ds.infrastructure.hyperspace.console.service.impl.SSOService;
import com.ds.infrastructure.hyperspace.console.service.inf.IAuthService;
import com.ds.infrastructure.hyperspace.console.service.inf.ISSOService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: yaozhendong
 * @create: 2019-11-18 10:43
 **/

@Slf4j
@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    ISSOService iSSOService;
    @Autowired
    IAuthService iAuthService;

    /**
     * 大坑，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken authenticationToken) {
        return authenticationToken instanceof ShiroToken;
    }

    /**
     * 权限验证（Authorization）-- 权限验证简称authz
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        try {
            ShiroToken.User currentUser = (ShiroToken.User) principalCollection.getPrimaryPrincipal();
            AuthService.AuthInfo authInfo = iAuthService.validateAuth(currentUser.getHttpMethod(), currentUser.getRequestURI(), currentUser.getId(), currentUser.getName());
            //验证失败
            if (!authInfo.isValidated()) {
                throw new UnauthorizedException(String.format("没有权限，禁止访问:Http Method=%s; Request URI=%s;", currentUser.getHttpMethod(), currentUser.getRequestURI()));
            }
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addStringPermission("*");
            return simpleAuthorizationInfo;
        } catch (Exception ex) {
            //此处的异常只能使用AuthenticationException的子类或本身，不能使用自定义异常类型
            throw new AuthorizationException("[AuthorizationException]:" + ex.getMessage());
        }
    }

    /**
     * 登录认证 （Authentication）-- 登录认证简称authc
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        ShiroToken shiroToken = (ShiroToken) authenticationToken;
        String sid = shiroToken.getCredentials().toString();
        try {
            //验证身份
            checkAuthentication(shiroToken, sid);
        } catch (Exception ex) {
            throw new AuthenticationException("AuthenticatedException:" + ex.getMessage());
        }
        try {
            //验证权限
            checkAuthorization(shiroToken);
        } catch (Exception ex) {
            throw new HAuthorizedException("AuthorizedException:" + ex.getMessage());
        }
        return new SimpleAuthenticationInfo(authenticationToken.getPrincipal(), authenticationToken.getCredentials(), "userRealm");
    }

    private void checkAuthentication(ShiroToken shiroToken, String sid) {
        //查询接口获得用户信息
        SSOService.UserInfo userInfo = iSSOService.getUserInfo(sid);
        shiroToken.setCurrentUser(userInfo.getUsername(), userInfo.getUid());
    }

    private void checkAuthorization(ShiroToken shiroToken) {
        ShiroToken.User currentUser = (ShiroToken.User) shiroToken.getPrincipal();
        AuthService.AuthInfo authInfo = iAuthService.validateAuth(currentUser.getHttpMethod(), currentUser.getRequestURI(), currentUser.getId(), currentUser.getName());
        //验证失败
        if (!authInfo.isValidated()) {
            throw new UnauthorizedException(String.format("没有权限，禁止访问:Http Method=%s; Request URI=%s;", currentUser.getHttpMethod(), currentUser.getRequestURI()));
        }
    }
}

